
package org.scalabletype.data;

import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.persistence.EntityManager;
import javax.servlet.ServletContext;

import com.spaceprogram.simplejpa.EntityManagerFactoryImpl;

public class DataHelper {
	private static EntityManagerFactoryImpl factory = null;

	public static void initDataHelper(String accessId, String secretKey, String className) {
		if (factory == null) {
			Map<String, String> props = new HashMap<String, String>();
			props.put("accessKey", accessId);
			props.put("secretKey", secretKey);
			Set<String> classNames = new HashSet<String>();
			classNames.add(className);
			factory = EntityManagerFactoryImpl.newInstanceWithClassNames("scalabletype", props, classNames);
		}
	}
	

	public static void initDataHelper(ServletContext context) {
		if (factory == null) {
			HashMap<String, String> props = new HashMap<String, String>();
			props.put("accessKey", getGlobalStringResource("aws.accessId"));
			props.put("secretKey", getGlobalStringResource("aws.secretKey"));

			String basePath = context.getRealPath("");
			Set<String> libPathsLocked = context.getResourcePaths("/WEB-INF/lib");
			Set<String> libPaths = new HashSet<String>();
			if(libPathsLocked != null){
				for (String s : libPathsLocked) {
					// need to prefix with full path
					libPaths.add(basePath + s);
				}
			}
			String path = context.getRealPath("/WEB-INF/classes");
			if (path != null) {
				File fp = new File(path);
				if (fp.exists()) libPaths.add(path);
			}

			factory = new EntityManagerFactoryImpl("scalabletype", props, libPaths);
		}
	}

	public static EntityManager getEntityManager() {
		return factory.createEntityManager();
	}

    public static String getGlobalStringResource(String propertyKey) {
        try {
            Context initContext = new InitialContext();
            Context context = (Context)initContext.lookup("java:comp/env");
            return (String)context.lookup(propertyKey);
        } catch (Exception ex) {
            System.err.println("Couldn't locate JNDI resource : "+propertyKey);
        }
        return "";
    }
}
